import java.util.ArrayList;

public class Library {
	private String name;
	private ArrayList<IUser> users;
	private ArrayList<ModelListener> listeners;

	private ArrayList<Integer> history;

	public ArrayList<Integer> getHistory() {
		return history;
	}

	public Library(String name) {
		this.name = name;
		//the arraylist is empty
		users = new ArrayList<IUser>();
		listeners = new ArrayList<ModelListener>();
		history = new ArrayList<Integer>();
		history.add(0);
	}
	//takes a user (IUser) as argument and adds the user to the arraylist of users for the library.
	public void addUser(IUser user) {
		users.add(user);
		history.add(totalBorrowedBooks());
		notifyListeners();
	}


	public void addListener(ModelListener listener) {
		listeners.add(listener);
	}
	private void notifyListeners() {
		for (int nextInt = 0; nextInt < listeners.size(); nextInt++) {
			listeners.get(nextInt).update();
		}
	}




	//returns as result the total number of books borrowed by all user
	public int totalBorrowedBooks()  {
		int total = 0;
		for(int i = 0; i < users.size(); i++) {
			total += users.get(i).getBook();
		}

		return total;
	}
	//takes as argument the name of a user and returns as result the number of books
	public int getBook(String name) throws UnknownUserException{
		for(int i = 0; i < users.size(); i++) {
			if(users.get(i).getName().equals(name)) {
				return users.get(i).getBook();
			}
		}
		throw new UnknownUserException("User " + name + " unknown.");
	}
	//takes as argument the name of a user and a number of books and changes the number of
	//books currently borrowed by that user
	public void moreBook(String name, int number) throws UnknownUserException, NotALenderException {
		for(int i = 0; i < users.size(); i++) {
			if(users.get(i).getName().equals(name)) {
				IUser iUser = users.get(i);
				iUser.moreBook(number);
				history.add(totalBorrowedBooks());
				notifyListeners();
				return;
			}
		}
		throw new UnknownUserException("User " + name + " unknown.");
	}
	public static void testLibrary() {
		Library li = new Library("UIC Library");
		System.out.println(li.totalBorrowedBooks() == 0);
		li.addUser(new Lender("L1", 10));
		try {
			System.out.println(li.getBook("L1") == -10);
			System.out.println(li.totalBorrowedBooks() == -10);
			li.addUser(new Borrower("B1", 20));
			System.out.println(li.getBook("L1") == -10);
			System.out.println(li.getBook("B1") == 20);
			System.out.println(li.totalBorrowedBooks() == 10);
			li.getBook("B2");
			li.moreBook("L1", 10);
			//System.out.println(li.getBook("L1") == 0);
		} catch(UnknownUserException ex) {
			System.out.println(ex.getMessage().equals("User B2 unknown."));
		} catch(NotALenderException ex) {
		// This should never happen!
			System.out.println(false);
		}
		
	}
}
